package com.utils;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

import com.alibaba.fastjson.JSONObject;
import com.car.common.model.Users;
import com.jfinal.kit.PropKit;

import io.rong.RongCloud;
import io.rong.messages.TxtMessage;
import io.rong.methods.message.system.MsgSystem;
import io.rong.methods.user.User;
import io.rong.models.Result;
import io.rong.models.message.MessageModel;
import io.rong.models.message.PrivateMessage;
import io.rong.models.message.SystemMessage;
import io.rong.models.response.ResponseResult;
import io.rong.models.user.UserModel;

public class RongCloudUtil {
	/**  融秀 一版本 */
//	private static String   appKey      = "z3v5yqkbz4bt0";
//	private static String   appSecret   = "i4UGllQ7iKoHS";
	/**  爱此时 二版本*/
	
	
//    private static String   appKey      = "z3v5yqkbzi8g0";
//    private static String   appSecret   = "oR6hULflDHa1";
    public static RongCloud rongCloud = null;
    static {
    	PropKit.use("config.properties");
    	String appKey 		=  PropKit.get("im.rongcloud.appKey");
    	String appSecret    =  PropKit.get("im.rongcloud.appSecret");
    	rongCloud  = RongCloud.getInstance(appKey, appSecret);
    }
 	       
    
    public static JSONObject post(String url, Map<String, String> params) {
    	HttpClient client = new HttpClient();
    	client.getParams().setContentCharset("UTF-8");
    	PostMethod postMethod = new PostMethod(url);
    	/**
    	 * // 重置随机数种子。
srand((double)microtime()*1000000);

$appSecret = 'Y1W2MeFwwwRxa0'; // 开发者平台分配的 App Secret。
$nonce = rand(); // 获取随机数。
$timestamp = time()*1000; // 获取时间戳（毫秒）。

$signature = sha1($appSecret.$nonce.$timestamp);
    	 */
    	
    	PropKit.use("config.properties");
    	String appKey 		=  PropKit.get("im.rongcloud.appKey");
    	String appSecret    =  PropKit.get("im.rongcloud.appSecret");
    	int nonce = new Random(100000).nextInt();
    	long timestamp = SystemClock.now(); 
    	
    	String signature = DigestUtils.shaHex(appSecret + nonce +"" + timestamp);
    	postMethod.setRequestHeader("App-Key",   	appKey);
    	postMethod.setRequestHeader("Nonce",     	String.valueOf(nonce));
    	postMethod.setRequestHeader("Timestamp",    String.valueOf(timestamp));
    	postMethod.setRequestHeader("Signature",    signature);
    
    	for(String key : params.keySet()) {
    		postMethod.addParameter(key, params.get(key));
    	}
    	try {
			int status = client.executeMethod(postMethod);
			if (status == HttpStatus.SC_OK) {
				String result = postMethod.getResponseBodyAsString();
				System.out.println(result);
				return JSONObject.parseObject(result);
			}
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
    
    
    public static void sendTxt(String send,String to,String content) {
    	String[] targetIds = {to};
    	TxtMessage txtMessage = new TxtMessage(content.replaceAll("\r\n", "").replaceAll("\n", "") , "extra");
    	 PrivateMessage privateMessage = new PrivateMessage()
                 .setSenderId(send)
                 .setTargetId(targetIds)
                 .setObjectName(txtMessage.getType())
                 .setContent(txtMessage)
                 //.setPushContent("hello")
                 //.setPushData("{\"pushData\":\"hello\"}")
                 .setCount("1")
                 .setVerifyBlacklist(0)
                 .setIsPersisted(0)
                 .setIsCounted(0)
                 .setIsIncludeSender(0);
		try {
			ResponseResult privateResult = RongCloudUtil.rongCloud.message.msgPrivate .send(privateMessage);
			System.out.println("send private message:  " + privateResult.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
         
    }
    
    public static void main(String[] args) throws Exception {
    	String[] targetIds = {"140901"};
    	TxtMessage txtMessage = new TxtMessage("hello 145", "helloExtra");
    	/*
         SystemMessage systemMessage = new SystemMessage()
                 .setSenderId("5072")
                 .setTargetId(targetIds)
                 .setObjectName(txtMessage.getType())
                 .setContent(txtMessage)
                 .setPushContent("this is a push")
                 .setPushData("{'pushData':'hello'}")
                 .setIsPersisted(0)
                 .setIsCounted(0)
                 .setContentAvailable(0);
        MsgSystem system = rongCloud.message.system;
		try {
			ResponseResult result = system.send(systemMessage);
			System.out.println("send system message:  " + result.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
    	/*
    	 PrivateMessage privateMessage = new PrivateMessage()
                 .setSenderId("145")
                 .setTargetId(targetIds)
                 .setObjectName(txtMessage.getType())
                 .setContent(txtMessage)
                 //.setPushContent("hello")
                 //.setPushData("{\"pushData\":\"hello\"}")
                 .setCount("4")
                 .setVerifyBlacklist(0)
                 .setIsPersisted(0)
                 .setIsCounted(0)
                 .setIsIncludeSender(0);
         ResponseResult privateResult = rongCloud.message.msgPrivate .send(privateMessage);
         
         System.out.println("send private message:  " + privateResult.toString());
        */
    	UserModel user = new UserModel()
                .setId("141")
                .setName("客服小姐姐")
                .setPortrait( "http://qiniu.static.50dufei.top//01c3da8794d21465fd8069bbd6fc2be3.png");
    	rongCloud.user.register(user);
	}
    
    public static void reg(Users users) throws Exception {
    	UserModel user = new UserModel()
                .setId(String.valueOf(users.getId()))
                .setName(StringUtil.decode(users.getNickName()))
                .setPortrait( (PicUtil.QINIU_DIR + users.getUserHeader()).replace("\\\\", "\\"));
    	rongCloud.user.register(user);
    }
    
    public static void update(Users users) throws Exception {
        //自定义 api 地址方式
        // RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);
//       rongCloud.user;
        UserModel user = new UserModel()
                .setId(String.valueOf(users.getId()))
                .setName(StringUtil.decode(users.getNickName()))
                .setPortrait( (PicUtil.QINIU_DIR + users.getUserHeader()).replace("\\\\", "\\"));
        
        Result refreshResult = rongCloud.user.update(user);
        System.out.println("refresh:  " + refreshResult.toString());
    }
}
